from typing import List

from fastapiApp.models.admin import Api_Mo, Menu_Mo, Role_Mo
from fastapiApp.schemas.role_schemas import *
from fastapi.exceptions import HTTPException

class RoleController(Role_Mo):
    def __init__(self):
        self.model=Role_Mo

    # 判断name是否已经存在
    async def is_exist(self, obj_in : RoleCreate) -> int:
        if await self.model.filter(name=obj_in.name).exists():
            raise HTTPException(status_code=400,detail="角色名已经存在")
        return 0

    # 权限修改
    async def update_roles(self, role: Role_Mo, menu_ids: List[int], api_infos: List[dict]) -> None:
        await role.menus.clear()
        for menu_id in menu_ids:
            menu_obj = await Menu_Mo.filter(id=menu_id).first()
            await role.menus.add(menu_obj)

        await role.apis.clear()
        for item in api_infos:
            api_obj = await Api_Mo.filter(path=item.get("path"), method=item.get("method")).first()
            await role.apis.add(api_obj)

    # 查看角色list
    async def list(self, page: int, page_size: int, role_name:str):
        query = await self.model.filter(name__icontains = role_name).offset((page - 1) * page_size).limit(page_size)
        count = await self.model.filter(name__icontains = role_name).count()
        data_list = [
            await role.to_dict()
            for role in query
        ]
        return count,data_list

role_controller = RoleController()
